package com.atlin.project.controller;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.Template;
import com.atlin.project.model.domain.User;
import com.atlin.project.model.dto.template.TemplateAddRequest;
import com.atlin.project.model.dto.template.TemplateQueryRequest;
import com.atlin.project.model.dto.template.TemplateUpdateRequest;
import com.atlin.project.model.vo.TemplateVO;
import com.atlin.project.service.TemplateService;
import com.atlin.project.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 模版接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/template")
public class TemplateController {

    @Resource
    private TemplateService templateService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param templateAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTemplate(@RequestBody TemplateAddRequest templateAddRequest, HttpServletRequest request) {
        if (templateAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Template template = new Template();
        BeanUtils.copyProperties(templateAddRequest, template);

        templateService.validTemplate(template, true);
        User loginUser = userService.getLoginUser(request);

        // todo

        boolean result = templateService.save(template);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newTemplateId = template.getId();
        return ResultUtils.success(newTemplateId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTemplate(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Template oldTemplate = templateService.getById(id);
        ThrowUtils.throwIf(oldTemplate == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        if (!oldTemplate.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = templateService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param templateUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTemplate(@RequestBody TemplateUpdateRequest templateUpdateRequest) {
        if (templateUpdateRequest == null || templateUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Template template = new Template();
        BeanUtils.copyProperties(templateUpdateRequest, template);

        // 参数校验
        templateService.validTemplate(template, false);
        long id = templateUpdateRequest.getId();
        // 判断是否存在
        Template oldTemplate = templateService.getById(id);
        ThrowUtils.throwIf(oldTemplate == null, ErrorCode.NULL_ERROR);
        // todo other operation
        
        boolean result = templateService.updateById(template);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Template> getTemplateById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Template template = templateService.getById(id);
        if (template == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!template.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(template);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TemplateVO> getTemplateVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Template template = templateService.getById(id);
        if (template == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        TemplateVO templateVO = new TemplateVO();
        BeanUtils.copyProperties(template, templateVO);
        return ResultUtils.success(templateVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param templateQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TemplateVO>> listTemplateVOByPage(@RequestBody TemplateQueryRequest templateQueryRequest,
                                                               HttpServletRequest request) {
        long current = templateQueryRequest.getCurrent();
        long size = templateQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Template> templatePage = templateService.page(new Page<>(current, size),
                new QueryWrapper<>());

        List<Template> templateList = templatePage.getRecords();

        Page<TemplateVO> templateVOPage = new Page<>(templatePage.getCurrent(), templatePage.getSize(), templatePage.getTotal());
        if (CollectionUtils.isEmpty(templateList)) {
            return ResultUtils.success(templateVOPage);
        }

        ArrayList<TemplateVO> templateVOList = new ArrayList<>();
        for (Template template : templateList) {
            TemplateVO templateVO = new TemplateVO();
            BeanUtils.copyProperties(template, templateVO);
            templateVOList.add(templateVO);
        }

        templateVOPage.setRecords(templateVOList);

        return ResultUtils.success(templateVOPage);
    }

    /**
     * 分页获取题目列表（仅管理员）
     *
     * @param templateQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Template>> listTemplateByPage(@RequestBody TemplateQueryRequest templateQueryRequest,
                                                           HttpServletRequest request) {
        long current = templateQueryRequest.getCurrent();
        long size = templateQueryRequest.getPageSize();
        Page<Template> templatePage = templateService.page(new Page<>(current, size),
                templateService.getQueryWrapper(templateQueryRequest));
        return ResultUtils.success(templatePage);
    }

    // endregion
    
}
